const userAuthPassword = require('../../model/userAuthPassword');
const UserInfo = require('../../model/userinfo');
const UserId = require("../../model/userid")
const userFriendsConfirm = require("../../model/userFriendsConfirm")
const userGroupMessage = require("../../model/userGroupMessage")
const userGroup = require("../../model/userGroup")
const { Op } = require("sequelize");
const ServerFindUserAccount = async (userAccount, userId) => {
    try {
        let user
        if (userAccount) {
            user = await userAuthPassword.findOne({
                where: {
                    userAccount
                },
                raw: true
            })
        }
        if (userId) {
            user = await userAuthPassword.findAll({
                where: {
                    userId
                },
                raw: true
            })
        }
        if (user) {
            return {
                data: user,
                isok: 1,
                message: "查询成功"
            }
        } else {
            return {
                data: {},
                isok: 0,
                message: "暂无数据"
            }
        }
    } catch (error) {
        console.log(error, "ServerFindUserAccount");
    }
}

// 根据邮箱查找用户
const ServerFindUserByEmail = async (email) => {
    try {
        // 先在UserInfo表中查找邮箱
        const userInfo = await UserInfo.findOne({
            where: {
                userMail: email
            },
            raw: true
        });

        if (!userInfo) {
            return {
                isok: false,
                message: "未找到与该邮箱关联的账号",
                data: null
            };
        }

        // 根据userId查找账号信息
        const userAuth = await userAuthPassword.findOne({
            where: {
                userId: userInfo.id
            },
            raw: true
        });

        if (!userAuth) {
            return {
                isok: false,
                message: "未找到该邮箱关联的登录信息",
                data: null
            };
        }

        return {
            isok: true,
            data: {
                ...userInfo,
                userAccount: userAuth.userAccount
            },
            message: "查询成功"
        };
    } catch (error) {
        console.error("根据邮箱查找用户出错:", error);
        return {
            isok: false,
            message: "查询用户失败",
            data: null
        };
    }
};

// 更新用户密码
const ServerUpdateUserPassword = async (userAccount, newPassword) => {
    try {
        // 更新密码
        const result = await userAuthPassword.update(
            { password: newPassword }, // 密码未加密，与登录验证保持一致
            {
                where: { userAccount: userAccount }
            }
        );

        if (result[0] > 0) {
            return {
                isok: true,
                message: "密码更新成功",
                data: {}
            };
        } else {
            return {
                isok: false,
                message: "密码更新失败，未找到用户",
                data: {}
            };
        }
    } catch (error) {
        console.error("更新用户密码出错:", error);
        return {
            isok: false,
            message: "更新密码失败",
            data: {}
        };
    }
};

module.exports = {
    ServerSetUserCount: async (userinfo) => {
        try {
            let resuserinfo = await UserInfo.create({
                userName: userinfo.username,
                userSex: userinfo.sex,
                userMail: userinfo.email,
                userAvatar: userinfo.avatar,
            })
            if (resuserinfo.dataValues) {
                let resuserAuthPassword = await userAuthPassword.create({
                    userId: resuserinfo.dataValues.id,
                    userAccount: userinfo.userAccount,
                    password: userinfo.password
                })
                if (resuserAuthPassword.dataValues) {
                    return {
                        isok: 1,
                        data: {
                            ...resuserinfo.dataValues,
                            ...resuserAuthPassword.dataValues
                        },
                        message: "创建成功"
                    }
                } else {
                    return {
                        isok: 0,
                        data: {},
                        message: "创建失败"
                    }
                }
            } else {
                return {
                    isok: 0,
                    data: {},
                    message: "创建失败"
                }
            }
        } catch (error) {
            console.log(error, "ServerSetUserCount");
        }
    },
    ServerFindUserAccount,
    ServerPasswordLogin: async (userAccount, password) => {
        const res = await userAuthPassword.findOne({
            where: {
                userAccount
            },
            raw: true
        })
        if (res) {
            if (res.password === password) {
                return {
                    isok: 1,
                    data: {},
                    message: "密码正确"
                }
            }
            return {
                isok: 0,
                data: {},
                message: "密码错误"
            }

        }
        return {
            isok: 0,
            data: {},
            message: "暂无用户"
        }
    },
    ServerGetUserInfo: async (userdata, isuserid = false) => {
        if (isuserid) {
            const userInfo = await UserInfo.findOne({
                where: {
                    id: userdata
                },
                raw: true
            })
            if (userInfo) {
                return {
                    isok: 1,
                    data: userInfo,
                    message: "查询成功"
                }
            } else {
                return {
                    isok: 0,
                    data: {},
                    message: "查询失败，暂无用户"
                }
            }
        } else {
            const userAccountIngfo = await ServerFindUserAccount(userdata)
            if (userAccountIngfo.isok) {
                const userInfo = await UserInfo.findOne({
                    where: {
                        id: userAccountIngfo.data.userId
                    },
                    raw: true
                })
                if (userInfo) {
                    return {
                        isok: 1,
                        data: userInfo,
                        message: "查询成功"
                    }
                } else {
                    return {
                        isok: 0,
                        data: {},
                        message: "查询失败，暂无用户"
                    }
                }
            } else {
                return {
                    isok: 0,
                    data: {},
                    message: "暂无此账户"
                }
            }
        }

    },
    ServerGetUSerInfoList: async (useridList) => {
        const userInfo = await UserInfo.findAll({
            where: {
                id: {
                    [Op.in]: useridList
                }
            },
            raw: true,
            attributes: { exclude: ['createdAt', "updatedAt"] }
        })
        if (userInfo.length) {
            return {
                isok: 1,
                data: userInfo,
                message: "查询成功"
            }
        }
        return {
            isok: 0,
            data: [],
            message: "暂无数据"
        }
    },
    ServerSetUserSockId: async (userId, socketid) => {
        const res = await UserId.create({
            userId,
            socketid
        })
        if (res) {
            return {
                isok: 1,
                data: res,
                message: "创建失败"
            }
        }
        return {
            isok: 0,
            data: {},
            message: "创建失败"
        }
    },
    ServerUpdataUserSockId: async (userId, socketid) => {
        const res = await UserId.update({ socketid: socketid }, {
            where: {
                userId
            },
            raw: true
        })
        if (res[0]) {
            return {
                isok: 1,
                data: res,
                message: "更新成功"
            }
        }
        return {
            isok: 0,
            data: {},
            message: "更新失败"
        }
    },
    ServerGetUserSockIdByID: async (userId) => {
        const res = await UserId.findOne({
            where: {
                userId: userId
            },
            raw: true
        })
        if (res) {
            return {
                isok: 1,
                data: res,
                message: "查询成功"
            }
        }
        return {
            isok: 0,
            data: {},
            message: "用户未创建过链接"
        }
    },
    ServerGetUserSockIdlistByIDList: async (useridList) => {
        const res = await UserId.findAll({
            where: {
                userId: {
                    [Op.in]: useridList
                }
            },
            raw: true
        })
        if (res) {
            return {
                isok: 1,
                data: res,
                message: "查询成功"
            }
        }
        return {
            isok: 0,
            data: {},
            message: "用户未创建过链接"
        }
    },
    ServerGetUserSockIdBySocketID: async (socketid) => {
        const res = await UserId.findOne({
            where: {
                socketid
            },
            raw: true
        })
        if (res) {
            return {
                isok: 1,
                data: res,
                message: "查询成功"
            }
        }
        return {
            isok: 0,
            data: {},
            message: "暂无socket的连接"
        }
    },
    ServerDestroySocket: async (id) => {
        const res = await UserId.destroy({
            where: {
                id
            }
        })
        if (res) {
            return {
                isok: 1,
                data: res,
                message: "删除成功"
            }
        }
        return {
            isok: 0,
            data: {},
            message: "删除失败"
        }
    },
    ServerGetSocketIdByUserId: async (userId) => {
        const res = await UserId.findOne({
            where: {
                userId
            },
            raw: true,
            attributes: ['socketid']
        })
        if (res.socketid) {
            return {
                isok: 1,
                data: res,
                message: "查询成功",

            }
        } else {
            return {
                isok: 0,
                data: {},
                message: "暂无socketid"
            }
        }
    },
    ServerSerchUser: async (keyword, userId, public = true) => {
        let friendlistdataid = []
        if (public) {
            const FriendsConfirm = await userFriendsConfirm.findAll({
                where: {
                    [Op.and]: {
                        [Op.or]: [
                            { userId: userId },
                            { friendUserId: userId }
                        ],
                        [Op.or]: [
                            { isConfirm: 1 },
                            { isConfirm: 3 },
                        ]
                    }
                },
                attributes: ["friendUserId", "userId"],
                raw: true
            })
            if (FriendsConfirm.length) {
                friendlistdataid = FriendsConfirm.map((item) => item.friendUserId == userId ? item.userId : item.friendUserId)
            }
        }
        const res = await UserInfo.findAll({
            where: {
                userName: {
                    [Op.like]: `%${keyword}%`,
                }
            },
            raw: true,
        })
        if (res.length) {
            return {
                isok: 1,
                data: res.map(item => {
                    return {
                        ...item,
                        isConfirm: friendlistdataid.includes(item.id) || false
                    }
                }),
                message: "获取成功"
            }
        }
        return {
            isok: 0,
            data: [],
            message: "暂无数据"
        }
    },
    ServerFinduserGroup: async (userId) => {
        const groupdata = await userGroupMessage.findAll({
            where: {
                userId: userId
            }
        }, { raw: true })
        const groupIdlist = groupdata?.map(item => item.groupId);
        const grouplist = await userGroup.findAll({
            where: {
                id: {
                    [Op.in]: groupIdlist
                }
            }
        }, { raw: true })
        if (grouplist.length) {
            return {
                isok: 1,
                message: "成功",
                data: grouplist.map(item => item.groupRoom)
            }
        }
        return {
            isok: 0,
            message: "失败",
            data: {}
        }
    },
    ServerUpdataUserInfo: async ({
        userid,
        avatar,
        username,
        sex,
        email,
        userSignature,
    }) => {
        const res = await UserInfo.update({
            userSex: sex,
            userMail: email,
            userName: username,
            userAvatar: avatar,
            userSignature
        }, {
            where: {
                id: userid
            }
        })
        const userinfo = await UserInfo.findOne({
            where: {
                id: userid
            }
        }, { raw: true })
        if (res) {
            return {
                isok: 1,
                message: "修改成功",
                data: userinfo
            }
        }
        return {
            isok: 0,
            message: "修改失败",
            data: {}
        }
    },
    ServerUpdateUserSignature: async (userId, userSignature) => {
        try {
            const result = await UserInfo.update(
                { userSignature },
                { where: { id: userId } }
            );

            if (result[0] > 0) {
                // 获取更新后的用户信息
                const updatedUser = await UserInfo.findOne({
                    where: { id: userId },
                    raw: true
                });

                return {
                    isok: 1,
                    data: updatedUser,
                    message: "更新签名成功"
                };
            } else {
                return {
                    isok: 0,
                    data: {},
                    message: "用户不存在或签名未更改"
                };
            }
        } catch (error) {
            console.error("更新签名失败:", error);
            return {
                isok: 0,
                data: {},
                message: "更新签名失败，服务器错误"
            };
        }
    },
    ServerFindUserByEmail,
    ServerUpdateUserPassword
}